package com.lifeverse.repository;

import com.lifeverse.entity.GroupDecision;
import com.lifeverse.entity.LifeEntity;
import com.lifeverse.entity.LifeEntityGroup;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 群体决策数据访问层
 */
@Repository
public interface GroupDecisionRepository extends JpaRepository<GroupDecision, Long> {
    
    /**
     * 根据群体查找决策
     */
    List<GroupDecision> findByGroup(LifeEntityGroup group);
    
    /**
     * 根据群体和状态查找决策
     */
    List<GroupDecision> findByGroupAndDecisionStatus(LifeEntityGroup group, GroupDecision.DecisionStatus status);
    
    /**
     * 根据决策类型查找决策
     */
    List<GroupDecision> findByDecisionType(GroupDecision.DecisionType decisionType);
    
    /**
     * 根据决策状态查找决策
     */
    List<GroupDecision> findByDecisionStatus(GroupDecision.DecisionStatus decisionStatus);
    
    /**
     * 根据优先级查找决策
     */
    List<GroupDecision> findByPriorityLevel(GroupDecision.PriorityLevel priorityLevel);
    
    /**
     * 根据提议者查找决策
     */
    List<GroupDecision> findByProposer(LifeEntity proposer);
    
    /**
     * 查找正在进行的决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.decisionStatus IN ('DISCUSSING', 'VOTING')")
    List<GroupDecision> findInProgressDecisions();
    
    /**
     * 查找已完成的决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.decisionStatus IN ('APPROVED', 'REJECTED', 'IMPLEMENTED', 'CANCELLED')")
    List<GroupDecision> findCompletedDecisions();
    
    /**
     * 查找已通过的决策
     */
    List<GroupDecision> findByDecisionStatusOrderByApprovedAtDesc(GroupDecision.DecisionStatus status);
    
    /**
     * 查找已实施的决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.decisionStatus = 'IMPLEMENTED' ORDER BY d.implementedAt DESC")
    List<GroupDecision> findImplementedDecisions();
    
    /**
     * 根据支持率范围查找决策
     */
    List<GroupDecision> findBySupportRateBetween(BigDecimal minRate, BigDecimal maxRate);
    
    /**
     * 查找高支持率决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.supportRate >= 80.0")
    List<GroupDecision> findHighSupportDecisions();
    
    /**
     * 根据置信度范围查找决策
     */
    List<GroupDecision> findByConfidenceScoreBetween(BigDecimal minScore, BigDecimal maxScore);
    
    /**
     * 查找高置信度决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.confidenceScore >= 80.0")
    List<GroupDecision> findHighConfidenceDecisions();
    
    /**
     * 根据质量评分范围查找决策
     */
    List<GroupDecision> findByQualityScoreBetween(BigDecimal minScore, BigDecimal maxScore);
    
    /**
     * 查找高质量决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.qualityScore >= 80.0")
    List<GroupDecision> findHighQualityDecisions();
    
    /**
     * 根据预期影响范围查找决策
     */
    List<GroupDecision> findByExpectedImpactBetween(BigDecimal minImpact, BigDecimal maxImpact);
    
    /**
     * 查找正面影响决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.expectedImpact > 0")
    List<GroupDecision> findPositiveImpactDecisions();
    
    /**
     * 查找负面影响决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.expectedImpact < 0")
    List<GroupDecision> findNegativeImpactDecisions();
    
    /**
     * 根据决策成本范围查找决策
     */
    List<GroupDecision> findByDecisionCostBetween(BigDecimal minCost, BigDecimal maxCost);
    
    /**
     * 查找高成本决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.decisionCost >= :threshold")
    List<GroupDecision> findHighCostDecisions(@Param("threshold") BigDecimal threshold);
    
    /**
     * 根据预期收益范围查找决策
     */
    List<GroupDecision> findByExpectedBenefitBetween(BigDecimal minBenefit, BigDecimal maxBenefit);
    
    /**
     * 查找高收益决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.expectedBenefit >= :threshold")
    List<GroupDecision> findHighBenefitDecisions(@Param("threshold") BigDecimal threshold);
    
    /**
     * 根据提议时间范围查找决策
     */
    List<GroupDecision> findByProposedAtBetween(LocalDateTime startTime, LocalDateTime endTime);
    
    /**
     * 查找最近提议的决策
     */
    List<GroupDecision> findTop10ByOrderByProposedAtDesc();
    
    /**
     * 查找最近通过的决策
     */
    List<GroupDecision> findTop10ByOrderByApprovedAtDesc();
    
    /**
     * 查找最近实施的决策
     */
    List<GroupDecision> findTop10ByOrderByImplementedAtDesc();
    
    /**
     * 查找过期的决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.deadline < :now AND d.decisionStatus IN ('PROPOSED', 'DISCUSSING', 'VOTING')")
    List<GroupDecision> findExpiredDecisions(@Param("now") LocalDateTime now);
    
    /**
     * 查找即将过期的决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.deadline BETWEEN :now AND :threshold AND d.decisionStatus IN ('PROPOSED', 'DISCUSSING', 'VOTING')")
    List<GroupDecision> findDecisionsNearDeadline(@Param("now") LocalDateTime now, @Param("threshold") LocalDateTime threshold);
    
    /**
     * 查找紧急决策
     */
    List<GroupDecision> findByPriorityLevelOrderByProposedAtDesc(GroupDecision.PriorityLevel priorityLevel);
    
    /**
     * 查找需要一致同意的决策
     */
    List<GroupDecision> findByRequiresConsensusTrue();
    
    /**
     * 根据参与人数范围查找决策
     */
    List<GroupDecision> findByParticipantsCountBetween(Integer minCount, Integer maxCount);
    
    /**
     * 查找高参与度决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.participantsCount >= :threshold")
    List<GroupDecision> findHighParticipationDecisions(@Param("threshold") Integer threshold);
    
    /**
     * 根据算法类型查找决策
     */
    List<GroupDecision> findByAlgorithmType(String algorithmType);
    
    /**
     * 根据标签查找决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.tags LIKE %:tag%")
    List<GroupDecision> findByTagsContaining(@Param("tag") String tag);
    
    /**
     * 统计决策数量按类型
     */
    @Query("SELECT d.decisionType, COUNT(d) FROM GroupDecision d GROUP BY d.decisionType")
    List<Object[]> countDecisionsByType();
    
    /**
     * 统计决策数量按状态
     */
    @Query("SELECT d.decisionStatus, COUNT(d) FROM GroupDecision d GROUP BY d.decisionStatus")
    List<Object[]> countDecisionsByStatus();
    
    /**
     * 统计决策数量按优先级
     */
    @Query("SELECT d.priorityLevel, COUNT(d) FROM GroupDecision d GROUP BY d.priorityLevel")
    List<Object[]> countDecisionsByPriority();
    
    /**
     * 计算平均支持率
     */
    @Query("SELECT AVG(d.supportRate) FROM GroupDecision d WHERE d.decisionStatus IN ('APPROVED', 'REJECTED')")
    BigDecimal calculateAverageSupportRate();
    
    /**
     * 计算平均决策时间（小时）
     */
    @Query("SELECT AVG(TIMESTAMPDIFF(HOUR, d.proposedAt, d.votingEndedAt)) FROM GroupDecision d WHERE d.votingEndedAt IS NOT NULL")
    Double calculateAverageDecisionTime();
    
    /**
     * 计算决策通过率
     */
    @Query("SELECT (COUNT(CASE WHEN d.decisionStatus = 'APPROVED' THEN 1 END) * 100.0 / COUNT(d)) FROM GroupDecision d WHERE d.decisionStatus IN ('APPROVED', 'REJECTED')")
    BigDecimal calculateApprovalRate();
    
    /**
     * 分页查询决策
     */
    Page<GroupDecision> findByGroup(LifeEntityGroup group, Pageable pageable);
    
    /**
     * 分页查询决策按状态
     */
    Page<GroupDecision> findByDecisionStatus(GroupDecision.DecisionStatus status, Pageable pageable);
    
    /**
     * 分页查询决策按类型
     */
    Page<GroupDecision> findByDecisionType(GroupDecision.DecisionType type, Pageable pageable);
    
    /**
     * 查找效率最高的决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.votingEndedAt IS NOT NULL ORDER BY TIMESTAMPDIFF(HOUR, d.proposedAt, d.votingEndedAt) ASC")
    List<GroupDecision> findMostEfficientDecisions(Pageable pageable);
    
    /**
     * 查找群体的最新决策
     */
    @Query("SELECT d FROM GroupDecision d WHERE d.group = :group ORDER BY d.proposedAt DESC")
    List<GroupDecision> findLatestDecisionsByGroup(@Param("group") LifeEntityGroup group, Pageable pageable);
}